package novel.front.novellist.controller;

import novel.common.web.BaseController;
import novel.front.novellist.pojo.WholeData;
import org.apache.commons.codec.binary.Base64;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by sutong on 2017/12/3.
 */
@Controller
@RequestMapping("poi")
public class poiController  extends BaseController {

    @RequestMapping("download")
    public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        String fileName = "整体数据";
//        Date startDate = sdf.parse(request.getParameter("sdate"));
//        Date endDate = sdf.parse(request.getParameter("edate"));
        Date startDate =new Date();
        Date endDate = new Date();
        Workbook workbook =  exportWholeReportByTpl11(startDate, endDate);

        fileDownload(request, response, workbook, fileName);
    }

    /**
     * 整体数据导出-使用模板文件
     *
     * @param startDate
     * @param endDate
     * @return
     */
    public Workbook exportWholeReportByTpl11(Date startDate, Date endDate) {
        // 准备数据
//        WholeData data = statMapper.getWholeData(startDate, dayAdd(endDate, 1));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        WholeData data = new WholeData();

        data.setAgent_order_count(1);
        data.setAgent_trade_amount(BigDecimal.valueOf(Long.parseLong("1")));
        data.setGoods_onshelves_count(1);
        data.setGoods_total_count(1);
        data.setMember_dealer_count(1);
        data.setMember_enterprise_count(1);
        data.setMember_personal_count(1);
        data.setMember_retailer_count(1);
        data.setMember_total_count(1);
        data.setAgent_order_count(1);
        data.setAgent_trade_amount(BigDecimal.valueOf(Long.parseLong("1")));
        data.setGoods_onshelves_count(1);
        data.setSelf_order_count(1);
        data.setSelf_trade_amount(BigDecimal.valueOf(Long.parseLong("1")));
        data.setShop_total_count(1);
        data.setTotal_order_count(1);
        data.setTotal_trade_amount(BigDecimal.valueOf(Long.parseLong("1")));

        String[] dataSrc = { sdf.format(startDate) + " 00:00:00", sdf.format(endDate) + " 23:59:59",
                data.getTotal_order_count().toString(), data.getSelf_order_count().toString(),
                data.getAgent_order_count().toString(), data.getTotal_trade_amount().toString(),
                data.getSelf_trade_amount().toString(), data.getAgent_trade_amount().toString(),
                data.getMember_total_count().toString(), data.getMember_enterprise_count().toString(),
                data.getMember_dealer_count().toString(), data.getMember_retailer_count().toString(),
                data.getMember_personal_count().toString(), data.getGoods_total_count().toString(),
                data.getGoods_onshelves_count().toString(), data.getShop_total_count().toString() };

        Workbook workbook = null;
        try {
            String tplPath = getTplPath("temp.xlsx");// 模板文件路径，注意是xlsx格式的excel文档
            FileInputStream tplFile = new FileInputStream(new File(tplPath));// 模板文件流

            workbook = new XSSFWorkbook(tplFile);// 工作簿
            Sheet sheet = workbook.getSheetAt(0);// 第一个工作表

            // 开始填充数据
            Row row0 = sheet.getRow(0);// 填充标题行，详见模板文件
            row0.getCell(0).setCellValue("灯亿网-整体数据");
            Row r= sheet.createRow(7);
            Row row3 = sheet.getRow(7);// 填充数据行，详见模板文件
            int len = dataSrc.length;

            // 创建单元格样式对象
            XSSFCellStyle ztStyle = (XSSFCellStyle) workbook.createCellStyle();
            ztStyle.setFillForegroundColor(new XSSFColor(Color.red));
            ztStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

            for (int i = 0; i < len; i++) {
                r.createCell(i);
                if (i==7){
                    r.getCell(i).setCellStyle(ztStyle);
                }
                row3.getCell(i).setCellValue(2);

            }

            // return saveFile2("整体数据", workbook);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return workbook;
    }

    /**
     * 整体数据导出-使用模板文件
     *
     * @param startDate
     * @param endDate
     * @return
     */
    public Workbook exportWholeReportByTpl(Date startDate, Date endDate) {
        // 准备数据
//        WholeData data = statMapper.getWholeData(startDate, dayAdd(endDate, 1));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        WholeData data = new WholeData();

        data.setAgent_order_count(1);
        data.setAgent_trade_amount(BigDecimal.valueOf(Long.parseLong("1")));
        data.setGoods_onshelves_count(1);
        data.setGoods_total_count(1);
        data.setMember_dealer_count(1);
        data.setMember_enterprise_count(1);
        data.setMember_personal_count(1);
        data.setMember_retailer_count(1);
        data.setMember_total_count(1);
        data.setAgent_order_count(1);
        data.setAgent_trade_amount(BigDecimal.valueOf(Long.parseLong("1")));
        data.setGoods_onshelves_count(1);
        data.setSelf_order_count(1);
        data.setSelf_trade_amount(BigDecimal.valueOf(Long.parseLong("1")));
        data.setShop_total_count(1);
        data.setTotal_order_count(1);
        data.setTotal_trade_amount(BigDecimal.valueOf(Long.parseLong("1")));

        String[] dataSrc = { sdf.format(startDate) + " 00:00:00", sdf.format(endDate) + " 23:59:59",
                data.getTotal_order_count().toString(), data.getSelf_order_count().toString(),
                data.getAgent_order_count().toString(), data.getTotal_trade_amount().toString(),
                data.getSelf_trade_amount().toString(), data.getAgent_trade_amount().toString(),
                data.getMember_total_count().toString(), data.getMember_enterprise_count().toString(),
                data.getMember_dealer_count().toString(), data.getMember_retailer_count().toString(),
                data.getMember_personal_count().toString(), data.getGoods_total_count().toString(),
                data.getGoods_onshelves_count().toString(), data.getShop_total_count().toString() };

        Workbook workbook = null;
        try {
            String tplPath = getTplPath("整体数据.xlsx");// 模板文件路径，注意是xlsx格式的excel文档
            FileInputStream tplFile = new FileInputStream(new File(tplPath));// 模板文件流

            workbook = new XSSFWorkbook(tplFile);// 工作簿
            Sheet sheet = workbook.getSheetAt(0);// 第一个工作表

            // 开始填充数据
            Row row0 = sheet.getRow(0);// 填充标题行，详见模板文件
            row0.getCell(0).setCellValue("灯亿网-整体数据");

            Row row3 = sheet.getRow(4);// 填充数据行，详见模板文件
            int len = dataSrc.length;
            for (int i = 0; i < len; i++) {
                row3.getCell(i).setCellValue(dataSrc[i]);
            }

            // return saveFile2("整体数据", workbook);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return workbook;
    }

    // 获取模板文件路径
    private String getTplPath(String tplName) {
        String path = getClass().getResource("/").getPath();
        path = path.substring(0, path.indexOf("WEB-INF"));
        path = path + "template/" + tplName;
        return path;
    }

    private void fileDownload(HttpServletRequest request, HttpServletResponse response, Workbook workbook,
                              String fileName) throws IOException {

        fileName = fileName + "-" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".xlsx";

        String agent = request.getHeader("USER-AGENT");
        if (agent != null && agent.toLowerCase().indexOf("firefox") > 0)// 针对火狐浏览器下载时中文乱码问题
        {
            fileName = "=?UTF-8?B?" + (new String(Base64.encodeBase64(fileName.getBytes("UTF-8")))) + "?=";
        } else {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        }

        response.setContentType("multipart/form-data");
        response.setHeader("content-disposition", "attachment;filename=" + fileName);

        OutputStream outputstream = response.getOutputStream();
        workbook.write(outputstream);
        outputstream.close();
    }

}
